﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Diagnostics;

namespace Jbe.TestSuite.CodeEditor.Domain
{
    class ProcessService
    {
        private Process p;
        public ProcessService()
        {
        }

        public void Run(string file)
        {
            p = new Process();
            p.StartInfo = new ProcessStartInfo();
            p.StartInfo.FileName = "ruby.exe";
            p.StartInfo.Arguments = file;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.EnableRaisingEvents = true;
            p.OutputDataReceived += new DataReceivedEventHandler(MyProcOutputHandler);
            p.ErrorDataReceived += new DataReceivedEventHandler(MyProcOutputHandler);
            p.Exited += new EventHandler(myProcess_HasExited);
            p.Start();
            // Start the asynchronous read of the sort output stream.
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
        }

        private void MyProcOutputHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
        {
            // Collect the sort command output. 
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                Application.Current.Dispatcher.Invoke(new Action(() => Log(outLine.Data)));
            }
        }

        private void myProcess_HasExited(object sender, System.EventArgs e)
        {
            Application.Current.Dispatcher.Invoke(
                new Action(() => Log("Process has exited:" + p.ExitCode.ToString())));
        }

        private static void Log(string message)
        {
            LogEntry entry = new LogEntry();
            entry.Message = message;
            entry.Title = "DynamicHelpService";
            entry.Categories.Add("Help");
            Logger.Write(entry);
        }
    }
}
